import { Bucket, Cluster, QueryOptions, Scope, connect } from 'couchbase'
// import { ENV_CONFIG } from './config'
import * as ENV_CONFIG from "./config.json";

/**
 * couchbase related services
 */
export class DatabaseService {
  constructor() {

  }
  private static instance: DatabaseService;
  cluster: Cluster;
  bucket: Bucket;
  scope: Scope;
  /**
   * Initial database connection
   */
  static async init() {
    try {
      await DatabaseService.getInstance();
      console.log("Db init success!");
    } catch (e) {
      console.error("Db init error", e);
    }
  }
  private async connect() {
    this.cluster = await connect(ENV_CONFIG.db.host, {
      username: ENV_CONFIG.db.username,
      password: ENV_CONFIG.db.password,
    });
    this.bucket = this.cluster.bucket(ENV_CONFIG.db.bucket);
    this.scope = this.bucket.scope(ENV_CONFIG.db.scope);
  }
  static async getInstance() {
    if (this.instance) {
      return this.instance;
    } else {
      this.instance = new DatabaseService();
      await this.instance.connect();
    }
  }
  
  static async getCollection(collection: string) {
    let ins = await this.getInstance();
    return ins.scope.collection(collection);
  }
  static async query(statement: string, options?: QueryOptions){
    let ins = await this.getInstance();
    let rst = await ins.scope.query(statement,options);
    return rst.rows;
  }
}